import { useModel } from 'umi';
import { Role } from '@/utils/types.d';
import { ModalForm, ProFormRadio, ProFormSelect } from '@ant-design/pro-components';
import { Button, Form, message } from 'antd';
import { useState } from 'react';
import { exportParkingspots, queryParkinglotNames } from '../service';
import { queryCompanies } from '@/pages/SystemUser/service';

export default () => {
  const { initialState } = useModel('@@initialState');
  const userRole = initialState?.currentUser?.role;
  const [exportType, setExportType] = useState<string>('all');
  const [parklotName, setParklotName] = useState<string>('');
  const [ownerName, setOwnerName] = useState<string>('');
  const [chillDowning, setChillDowning] = useState<number>(0);
  const [form] = Form.useForm();
  if (chillDowning > -1) {
    setTimeout(() => {
      setChillDowning(chillDowning - 1);
    }, 1000);
  }
  return (
    <ModalForm
      title="泊位数据导出"
      submitter={false}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      width={600}
      form={form}
      modalProps={{
        destroyOnClose: true,
      }}
      trigger={<Button>泊位数据导出</Button>}
    >
      <ProFormRadio.Group
        radioType="button"
        label="导出类型"
        initialValue={exportType}
        fieldProps={{
          value: exportType,
          onChange: (e) => setExportType(e.target.value),
        }}
        options={
          userRole === Role.ADMIN
            ? [
                { label: '按照用户', value: 'enterprise' },
                { label: '按照路段', value: 'parkinglot' },
                { label: '全量导出', value: 'all' },
              ]
            : [
                { label: '按照路段', value: 'parkinglot' },
                { label: '全量导出', value: 'all' },
              ]
        }
      />
      {exportType === 'enterprise' && (
        <ProFormSelect
          width="md"
          label="选择用户"
          name="ownerId"
          required
          debounceTime={300}
          placeholder="请选择所属用户"
          fieldProps={{
            onChange: (_, option: any) => {
              if (option) setOwnerName(option.label);
            },
          }}
          showSearch
          request={(val) => queryCompanies(val.keyWords)}
        />
      )}
      {exportType === 'parkinglot' && (
        <ProFormSelect
          width="md"
          label="选择路段"
          name="parkingLotId"
          debounceTime={300}
          required
          placeholder="请选择路段"
          fieldProps={{
            onChange: (_, option: any) => {
              if (option) setParklotName(option.label);
            },
          }}
          showSearch
          request={(val) => queryParkinglotNames(val.keyWords)}
        />
      )}
      <div
        style={{
          margin: '0 auto',
          width: '60%',
          padding: '15px 0',
          verticalAlign: 'middle',
          textAlign: 'center',
          background: '#f4f6fa',
        }}
      >
        <p style={{ marginTop: 0 }}>按照用户：选择指定用户名下车位数据导出</p>
        <p>按照路段：选择指定路段下的车位数据导出</p>
        <p style={{ marginBottom: 0 }}>全量导出：导出当前用户名下所有车位数据</p>
      </div>
      <Button
        disabled={chillDowning > 0}
        type="primary"
        style={{
          margin: '20px auto',
          display: 'block',
          textAlign: 'center',
        }}
        onClick={async () => {
          const params = form.getFieldsValue();
          if (exportType == 'parkinglot' && !params.parkingLotId) {
            message.error({ key: 'export_spot', content: '请选择路段' });
            return false;
          }
          if (exportType == 'enterprise' && !params.ownerId) {
            message.error({ key: 'export_spot', content: '请选择路段' });
            return false;
          }
          setChillDowning(60);
          message.info({ key: 'export_file', content: '正在导出文件，请稍后……' });

          const res = await exportParkingspots(params);
          let filename = `泊位列表_`;
          if (params.ownerId) filename += `${ownerName}_`;
          if (params.parkingLotId) filename += `${parklotName}_`;
          filename += `${new Date().toLocaleString()}.xlsx`;
          const downloadElement = document.createElement('a');
          const herf = window.URL.createObjectURL(
            new Blob([res], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            }),
          );
          downloadElement.href = herf;
          downloadElement.download = filename;
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(herf); // 释放blob对象

          return true;
        }}
      >
        {chillDowning <= 0 ? '下载Excel格式文件' : `等待（${chillDowning}）`}
      </Button>
    </ModalForm>
  );
};
